package com.dc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dc.common.ResponseResultVO;
import com.dc.constat.SystemConfigConstant;
import com.dc.constat.SystemConstant;
import com.dc.entity.*;
import com.dc.entity.ro.SysUserRO;
import com.dc.entity.ro.SysUserRoleRO;
import com.dc.mapper.*;
import com.dc.service.SysUserRoleService;
import com.dc.service.SysUserService;
import com.dc.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 管理员用户接口实现
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysDataSourceMapper sysDataSourceMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SysTenantMapper sysTenantMapper;

    @Resource
    private SysConfigMapper sysConfigMapper;


    @Override
    @Transactional
    public ResponseResultVO insert(SysUserRO sysUserRO) {
        if (StringUtils.isBlank(sysUserRO.getLoginName())) {
            return ResponseResultVO.failResult("登录名不能为空");
        } else if (!sysUserRO.getLoginName().matches(SystemConstant.LOGIN_NAME_REGEX)) {
            return ResponseResultVO.failResult("登录名必需以字母、数字开头的5-20位字符，只能包含字母、数字、下划线'_'");
        }
        if (StringUtils.isBlank(sysUserRO.getPassword())) {
            return ResponseResultVO.failResult("密码不能为空");
        } else if (!sysUserRO.getPassword().matches(SystemConstant.PWD_REGEX)) {
            return ResponseResultVO.failResult("密码必需以字母、数字开头的6-16位字符，只能包含字母、数字、下划线'_'");
        }
        if (StringUtils.isBlank(sysUserRO.getMobile())) {
            return ResponseResultVO.failResult("手机号不能为空");
        }
        SysUser dbSysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getLoginName, sysUserRO.getLoginName()));
        if (null != dbSysUser) {
            return ResponseResultVO.failResult("该账号名已被使用");
        }
        QueryWrapper<SysUser> queryWrapperPhone = new QueryWrapper<>();
        queryWrapperPhone.eq("mobile", sysUserRO.getMobile());
        List<SysUser> sysUserDTOS1 = sysUserMapper.selectList(queryWrapperPhone);
        if (!CollectionUtils.isEmpty(sysUserDTOS1)) {
            return ResponseResultVO.failResult("手机号已被使用");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(SnowflakeIdWorker.generateId());
        sysUser.setLoginName(sysUserRO.getLoginName());
        sysUser.setSex(sysUserRO.getSex());
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserRO.getPassword().getBytes()));
        if (StringUtils.isBlank(sysUserRO.getUserName())) {
            sysUser.setUserName(sysUserRO.getLoginName());
        } else {
            sysUser.setUserName(sysUserRO.getUserName());
        }
        sysUser.setMobile(sysUserRO.getMobile());
        sysUser.setIsSuper(0);
        sysUser.setStatus(0);
        if (StringUtils.isNotBlank(sysUserRO.getCardNumber())) {
            sysUser.setCardNumber(sysUserRO.getCardNumber());
        }
        sysUserMapper.insert(sysUser);

        // 关联角色数据
        if (StringUtils.isNotBlank(sysUserRO.getRoleId())) {
            List<String> roleIds = Arrays.asList(sysUserRO.getRoleId().split(","));
            for (String id : roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setId(SnowflakeIdWorker.generateId());
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId(Long.valueOf(id));
                //批量插入
                sysUserRoleService.save(sysUserRole);
            }
        }

        // 关联数据源
        if (StringUtils.isNotBlank(sysUserRO.getDataSourceId())) {
            List<String> dataSourceIds = Arrays.asList(sysUserRO.getDataSourceId().split(","));
            for (String id : dataSourceIds) {
                SysTenant sysTenant = new SysTenant();
                sysTenant.setId(SnowflakeIdWorker.generateId());
                sysTenant.setUserId(sysUser.getId());
                sysTenant.setSourceId(Long.valueOf(id));
                //批量插入
                sysTenantMapper.insert(sysTenant);
            }
        }


        return ResponseResultVO.successResult("新增成功");
    }


    @Override
    @Transactional
    public ResponseResultVO insertDataSource(SysDataSource sysDataSource) {
        SysConfig sysConfig = sysConfigMapper.selectOne(new QueryWrapper<SysConfig>().lambda().eq(SysConfig::getConfigKey, SystemConfigConstant.data_source));
        String content = "";
        if (null != sysConfig) {
            String configValue = sysConfig.getConfigValue();
            content = configValue.replace("basic_data", sysDataSource.getName());
        }
        ScriptRunnerExecSql.addSource(sysDataSource.getHost(), sysDataSource.getUsername(), sysDataSource.getPassword(), sysDataSource.getPort(), content);
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        int i = sysDataSourceMapper.insert(sysDataSource);
        objectObjectHashMap.put("url", sysDataSource.getUrl());
        objectObjectHashMap.put("username", sysDataSource.getUsername());
        objectObjectHashMap.put("password", sysDataSource.getPassword());
        objectObjectHashMap.put("id", sysDataSource.getId());
        redisUtil.set("dataSource:" + sysDataSource.getId(), objectObjectHashMap);
        return ResponseResultVO.insertResult(i);
    }

    @Override
    @Transactional
    public ResponseResultVO updateDataSource(String id) {
        String userId = UserUtil.getUserId();
        List<SysTenant> sysTenants = sysTenantMapper.selectList(new QueryWrapper<SysTenant>().lambda().eq(SysTenant::getUserId, userId).eq(SysTenant::getSourceId, id));
        if (CollectionUtils.isEmpty(sysTenants)) {
            return ResponseResultVO.failResult("当前用户没有该数据源");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(userId));
        sysUser.setTenantId(id);
        sysUserMapper.updateById(sysUser);
        return null;
    }

    @Override
    @Transactional
    public ResponseResultVO delete(String id) {
        //查询最后一次登录的token
        SysUser sysUser = sysUserMapper.selectById(id);
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, id));
        redisUtil.del("token:" + sysUser.getToken());
        return ResponseResultVO.deleteResult(sysUserMapper.deleteById(id));
    }

    @Override
    @Transactional
    public ResponseResultVO update(SysUserRO sysUserRO) {
        if (null == sysUserRO.getId()) {
            return ResponseResultVO.failResult("用户id不能为空");
        }
        SysUser dbSysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getLoginName, sysUserRO.getLoginName()).ne(SysUser::getId, sysUserRO.getId()));
        if (null != dbSysUser) {
            return ResponseResultVO.failResult("该账号名已被使用");
        }
        if (!sysUserRO.getLoginName().matches(SystemConstant.LOGIN_NAME_REGEX)) {
            return ResponseResultVO.failResult("登录名必需以字母、数字开头的5-20位字符，只能包含字母、数字、下划线'_'");
        }
        if (StringUtils.isNotEmpty(sysUserRO.getPassword())) {
            if (!sysUserRO.getPassword().matches(SystemConstant.PWD_REGEX)) {
                return ResponseResultVO.failResult("密码必需以字母、数字开头的6-16位字符，只能包含字母、数字、下划线'_'");
            }
        }
        if (StrUtil.isNotBlank(sysUserRO.getMobile())) {
            QueryWrapper<SysUser> queryWrapperPhone = new QueryWrapper<>();
            queryWrapperPhone.eq("mobile", sysUserRO.getMobile());
            List<Long> ids = new ArrayList<>();
            ids.add(sysUserRO.getId());
            List<SysUser> sysUserDTOS1 = sysUserMapper.selectList(queryWrapperPhone.notIn("id", ids));
            if (!CollectionUtils.isEmpty(sysUserDTOS1)) {
                return ResponseResultVO.failResult("手机号已被使用");
            }
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserRO, sysUser);
        if (StringUtils.isNotBlank(sysUserRO.getPassword())) {
            sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserRO.getPassword().getBytes()));
            SysUser selectById = sysUserMapper.selectById(sysUserRO.getId());
            redisUtil.del("token:" + selectById.getToken());
        } else {
            sysUser.setPassword(null);
        }

        // 关联角色数据
        if (StringUtils.isNotBlank(sysUserRO.getRoleId())) {
            sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, sysUserRO.getId()));
            List<String> roleIds = Arrays.asList(sysUserRO.getRoleId().split(","));
            for (String id : roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(Long.valueOf(id));
                sysUserRole.setId(SnowflakeIdWorker.generateId());
                sysUserRole.setUserId(sysUserRO.getId());
                sysUserRoleMapper.insert(sysUserRole);
            }
        }

        int num = sysUserMapper.updateById(sysUser);
        return ResponseResultVO.updateResult(num);
    }

    @Override
    public ResponseResultVO updateUserInfo(SysUserRO sysUserRO) {
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(UserUtil.getUserId()));
        sysUser.setSex(sysUserRO.getSex());
        sysUser.setMobile(sysUserRO.getMobile());
        sysUser.setUserName(sysUserRO.getUserName());
        return ResponseResultVO.updateResult(sysUserMapper.updateById(sysUser));
    }

    @Override
    public ResponseResultVO updateUserPwd(SysUserRO sysUserRO) {
        Long userId = Long.valueOf(UserUtil.getUserId());
        SysUser oldUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getId, userId));
        String oldUserPassword = oldUser.getPassword();
        if (!oldUserPassword.equalsIgnoreCase(DigestUtils.md5DigestAsHex(sysUserRO.getOldPassword().getBytes()))) {
            return ResponseResultVO.failResult("旧密码输入有误,请重新填写!");
        }
        if (StringUtils.isNotEmpty(sysUserRO.getPassword())) {
            if (!sysUserRO.getPassword().matches(SystemConstant.PWD_REGEX)) {
                return ResponseResultVO.failResult("密码必需以字母、数字开头的6-16位字符，只能包含字母、数字、下划线'_'");
            }
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(UserUtil.getUserId()));
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserRO.getPassword().getBytes()));
        return ResponseResultVO.updateResult(sysUserMapper.updateById(sysUser));
    }

    @Override
    public ResponseResultVO updatePortrait(String portrait) {
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(UserUtil.getUserId()));
        sysUser.setPortrait(portrait);
        return ResponseResultVO.updateResult(sysUserMapper.updateById(sysUser));
    }

    @Override
    public ResponseResultVO unlock(String id) {
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(id));
        sysUser.setErrorCount(0);
        return ResponseResultVO.updateResult(sysUserMapper.updateById(sysUser));
    }

    @Override
    public ResponseResultVO selectById(String id) {
        SysUser sysUser = this.sysUserMapper.selectById(id);
        // 查询用户角色
        List<SysRole> sysRoles = getSysRoleDTOS(id);
        if (!CollectionUtils.isEmpty(sysRoles)) {
            sysUser.setRoleList(sysRoles);
        }
        return ResponseResultVO.successResult(sysUser);
    }

    private List<SysRole> getSysRoleDTOS(String id) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        List<Long> list = new ArrayList<>();
        for (SysUserRole sysUserRole : sysUserRoles) {
            list.add(sysUserRole.getRoleId());
        }
        QueryWrapper<SysRole> sysRoleDTOQueryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(list)) {
            sysRoleDTOQueryWrapper.in("id", list);
        } else {
            return null;
        }
        return sysRoleMapper.selectList(sysRoleDTOQueryWrapper);
    }

    @Override
    public ResponseResultVO selectSysUserList(SysUserRO userRO) {
        Page page = new Page<Map<String, Object>>(userRO.getCurrentPage(), userRO.getPageSize());
        return ResponseResultVO.resultList(sysUserMapper.selectSysUserList(page, userRO), userRO);
    }

    @Override
    public ResponseResultVO selectAllUser() {
        return ResponseResultVO.successResult(sysUserMapper.selectList(new QueryWrapper<>()));
    }

    @Override
    public ResponseResultVO updateSysUserRole(SysUserRoleRO ro) {
        if (ro.getUserId() == null) {
            return ResponseResultVO.failResult("用户id不能为空");
        }
        if (ro.getRoleId() == null) {
            return ResponseResultVO.failResult("角色id不能为空");
        }

        if (ro.getOpType() == null || ro.getOpType() != 1) {
            SysUserRole sysUserRole = new SysUserRole();
            BeanUtils.copyProperties(ro, sysUserRole);
            sysUserRole.setId(SnowflakeIdWorker.generateId());
            sysUserRoleMapper.insert(sysUserRole);

        } else {
            // 删除
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", ro.getUserId());
            queryWrapper.eq("role_id", ro.getRoleId());
            int num = sysUserRoleMapper.delete(queryWrapper);
            if (num <= 0) {
                return ResponseResultVO.failResult("失败");
            }
        }
        return ResponseResultVO.successResult("成功");

    }

    @Override
    public ResponseResultVO selectSysUserRoleList(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResultVO.failResult("用户id不能为空");
        }
        List<SysRole> sysRoles = getSysRoleDTOS(id);

        return ResponseResultVO.successResult(sysRoles);
    }


}
